package com.heima.schedule.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.common.constants.ScheduleConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.schedule.dtos.TaskDto;
import com.heima.model.schedule.pojos.Taskinfo;
import com.heima.model.schedule.pojos.TaskinfoLogs;
import com.heima.schedule.mapper.TaskinfoLogsMapper;
import com.heima.schedule.mapper.TaskinfoMapper;
import com.heima.schedule.service.TaskService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Set;

@Slf4j
@Service
@Transactional
public class TaskServiceImpl implements TaskService {
    @Autowired
    private TaskinfoMapper taskinfoMapper;
    @Autowired
    private TaskinfoLogsMapper taskinfoLogsMapper;
    @Autowired
    private CacheService cacheService;

    /**
     * 添加任务
     * * 1.向数据库表taskinfo  taskinfo_logs插入数据
     * * 2.根据任务的执行时间,向reids的list / zset中添加数据
     *
     * @param task
     * @return 任务id
     */
    @Override
    public long addTask(TaskDto task) {
        if (task == null) return -1;
        long taskId = IdWorker.getId();
        task.setTaskId(taskId);

        //1.将任务添加到db中
        boolean isOk = addTaskToDB(task);

        //2.将任务添加到redis中
        if (isOk) {
            addTaskToRedis(task);
        }
        //返回任务id
        return taskId;
    }

    /**
     * 将任务添加到redis中
     * 1.如果任务的执行时间小于等于当前时间,那么就存入redis的list中
     * 2.如果任务的执行时间大于当前时间,小于等于未来5分钟的时间,那么就根据将执行时间作为"分数"存入zset中
     *
     * @param task
     */
    private void addTaskToRedis(TaskDto task) {
        //实际使用过程中参数key = 1001_1
        String key = task.getTaskType() + "_" + task.getPriority();

        //2.1如果任务的执行时间 小于等于当前时间, 存入list中
        if (task.getExecuteTime() <= System.currentTimeMillis()) {
            cacheService.lLeftPush(ScheduleConstants.TOPIC + key, JSON.toJSONString(task)); //实际key = topic_1001_1

        } else if (task.getExecuteTime() > System.currentTimeMillis() && task.getExecuteTime() <= System.currentTimeMillis() + (1000 * 60 * 5)) {
            //2.2如果任务的执行时间 大于当前时间,小于等于未来时间(当前时间+5分钟), 存入zset中
            cacheService.zAdd(ScheduleConstants.FUTURE + key, JSON.toJSONString(task), task.getExecuteTime());
        }
    }

    /**
     * 向数据库任务表taskinfo ,任务日志表taskinfo_logs中插入数据
     *
     * @param dto
     * @return
     */
    private boolean addTaskToDB(TaskDto dto) {
        boolean flag = true;

        try {
            Taskinfo taskinfo = new Taskinfo();
            BeanUtils.copyProperties(dto, taskinfo);
            taskinfo.setExecuteTime(new Date(dto.getExecuteTime()));

            taskinfoMapper.insert(taskinfo);

            //存入taskinfo_logs
            TaskinfoLogs taskinfoLogs = new TaskinfoLogs();
            BeanUtils.copyProperties(taskinfo, taskinfoLogs);
            taskinfoLogs.setVersion(1);
            taskinfoLogs.setStatus(ScheduleConstants.SCHEDULED);

            taskinfoLogsMapper.insert(taskinfoLogs);
        } catch (Exception e) {
            flag = false;
            e.printStackTrace();
        }


        return flag;
    }


    /**
     * 从reids的list集合中拉取任务
     *
     * @param taskType 任务类型
     * @param priority 任务优先级
     * @return 返回任务
     */
    @Override
    public TaskDto popTask(Integer taskType, Integer priority) {
        String key = ScheduleConstants.TOPIC + taskType + "_" + priority;
        //1.将任务从reids中取出
        String taskJson = cacheService.lRightPop(key);
        if (StringUtils.isBlank(taskJson)) {
            return null;
        }
        TaskDto taskDto = JSON.parseObject(taskJson, TaskDto.class);

        //2.删除数据库taskinfo表中的记录,更新taskinfo_logs表
        taskinfoMapper.deleteById(taskDto.getTaskId());

        TaskinfoLogs taskinfoLogs =
                taskinfoLogsMapper.selectOne(Wrappers.<TaskinfoLogs>lambdaQuery()
                        .eq(TaskinfoLogs::getTaskId, taskDto.getTaskId()));
        taskinfoLogs.setStatus(ScheduleConstants.EXECUTED);
        taskinfoLogsMapper.updateById(taskinfoLogs);

        return taskDto;
    }


    /**
     * 定时刷新redis: zset中的未来任务数据,刷新到list中
     * 每分钟刷新一次
     */
    @Scheduled(cron = "0 */1 * * * ?")
    public void refreshRedis() {
        log.info("定时刷新redis....每分钟刷新一次,将zset中符合条件的任务数据刷新到list中...");
        //1.先获取到zset中所有的键
        Set<String> zSetKeys = cacheService.scan(ScheduleConstants.FUTURE + "*");  //future_1001_1
        for (String futureKey : zSetKeys) {
            //构建topickey
            String topicKey = ScheduleConstants.TOPIC + futureKey.split(ScheduleConstants.FUTURE)[1]; //topic_1001_1

            //2.根据获取到的键和执行时间,匹配符合的任务
            Set<String> tasks = cacheService.zRangeByScore(futureKey, 0, System.currentTimeMillis());
            if (tasks != null) {
                //3.将符合条件的任务刷到list中
                cacheService.refreshWithPipeline(futureKey, topicKey, tasks);
                log.info("成功将" + futureKey + "刷新到了" + topicKey);
            }
        }

    }


    /**
     * 将数据库中的任务数据定时同步到redis中
     */
    @PostConstruct             //Bean的初始化方法,当bean被创建好后,会自动执行该方法,只执行一次
    @Scheduled(cron = "0 */5 * * * ?")
    public void refreshDBToRedis() {
        log.info("数据库定时数据同步,将db中5分钟内的任务同步到redis中...");
        //1.清空redis缓存
        Set<String> futureKeys = cacheService.scan(ScheduleConstants.FUTURE + "*");
        Set<String> topicKeys = cacheService.scan(ScheduleConstants.TOPIC + "*");
        cacheService.delete(futureKeys);
        cacheService.delete(topicKeys);

        //2.查询db中满足条件的任务
        Date futureDate = new Date(System.currentTimeMillis() + (1000 * 60 * 5));
        List<Taskinfo> taskinfos = taskinfoMapper.selectList(Wrappers.<Taskinfo>lambdaQuery().le(Taskinfo::getExecuteTime, futureDate));

        //3.将查询到的任务同步到redis中
        if (taskinfos != null && taskinfos.size() > 0) {
            for (Taskinfo taskinfo : taskinfos) {
                TaskDto dto = new TaskDto();
                BeanUtils.copyProperties(taskinfo, dto);
                dto.setExecuteTime(taskinfo.getExecuteTime().getTime());

                addTaskToRedis(dto);
            }
        }
    }
}
